package SortAlgorithm;

import com.alibaba.fastjson.JSON;

import java.util.Arrays;

public class 选择排序 implements ISort{

    /**
     * 从 [0..n] 依次遍历,放入将小的数依次排好队,放在左边。
     */

    @Override
    public int[] sort(int[] arr) {
        return selectionSort(arr);
    }

    public int[] selectionSort(int[] arr){

        int left=0;
        int minIndex=0;
        int minNum;

        for (int i = left; i < arr.length; i++) {
            minIndex=left;
            minNum=arr[left];
            for (int j = i+1; j < arr.length; j++) {
                //找出最小的数
                if(arr[j]<minNum){
                    minIndex=j;
                    minNum=arr[j];
                }
            }
            swap(arr,left,minIndex);
            left++;
        }

        return arr;
    }

    private void swap(int[] arr,int index1,int index2){
        int temp=arr[index1];
        arr[index1]=arr[index2];
        arr[index2]=temp;
    }

    public static void main(String[] args) {
        选择排序 n=new 选择排序();
        int[] arr={4,2,3,4,5,6,1,2,4,3,5,1,5,2,5,6,1,2,5};
        int[] result = n.selectionSort(arr);
        System.out.println(JSON.toJSONString(result));
        Arrays.sort(arr);
        System.out.println(JSON.toJSONString(arr));
    }

}
